from exts import db
from common import constant
from common.base_model import BasicModelMixin, \
    CompanyMixin, CreateMixin, UpdateMixin, DeleteMixin
from app.message import dingding_service

MIDDLE_DB_STR_LEN = constant.MIDDLE_DB_STR_LEN
LONG_DB_STR_LEN = constant.LONG_DB_STR_LEN


# 用户消息
class Message(db.Model, BasicModelMixin,
              CompanyMixin, CreateMixin, UpdateMixin, DeleteMixin):
    __tablename__ = 'message'

    id = db.Column(db.Integer, primary_key=True)
    msg_type = db.Column(db.String(MIDDLE_DB_STR_LEN),
                         default=constant.MessageType.SYSTEM)
    sender_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    sender = db.relationship("User", foreign_keys='Message.sender_id')

    receiver_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    receiver = db.relationship("User", foreign_keys='Message.receiver_id')

    title = db.Column(db.String(LONG_DB_STR_LEN))
    content = db.Column(db.String(LONG_DB_STR_LEN))
    # 用于快速跳转
    ext_parameters = db.Column(db.JSON)

    is_receive = db.Column(db.Boolean, default=False)
    is_read = db.Column(db.Boolean, default=False)

    def send_msg_to_dingding(self):
        # 处理下body
        dingding_service.send_msg_to_dingding(
            self.content, dingding_service.get_dingding_url(),
            at_mobiles=[self.receiver.phone])
